package com.wgworkshop.pems.service;

import com.wgworkshop.pems.entity.UserEntity;
import com.wgworkshop.pems.model.UserModel;
import com.wgworkshop.pems.repository.UserRepository;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

/**
 * 用户服务接口实现类。
 * Created by lcwang on 2018/3/23.
 */
@Service
public class UserServiceImpl implements UserService {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Integer expiration;
    @Value("${jwt.audience}")
    private String audience;

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserModel login(UserModel userModel) {
        String account = userModel.getAccount();
        String password = DigestUtils.md5DigestAsHex(userModel.getPassword().getBytes());
        UserEntity userEntity = userRepository.findFirstByAccountAndPassword(account, password);

        UserModel resultModel = new UserModel();
        if (userEntity != null) {
            String token = Jwts.builder()
                    .setSubject(userEntity.getAccount())
                    .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                    .setAudience(audience)
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .compact();

            resultModel = toModel(userEntity);
            resultModel.setToken(token);
        }

        return resultModel;
    }

    @Override
    public UserModel getUserByAccount(String account) {
        UserEntity userEntity = userRepository.findFirstByAccount(account);
        return toModel(userEntity);
    }

    private UserModel toModel(UserEntity userEntity) {
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(userEntity, userModel);
        return userModel;
    }
}
